/**
 * OSAmI: Open Source Ambient Intelligence
 * Copyright (C) 2010 Université Joseph Fourier
 * Contact: osami-general@osami-commons.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 */
package org.osami.gateway.mediator.jms.sender;

import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.naming.InitialContext;

import org.osgi.service.log.LogService;

import fr.liglab.adele.cilia.CiliaException;
import fr.liglab.adele.cilia.Data;
import fr.liglab.adele.cilia.framework.ISender;

/**
 * This mediator send all the data it receives on a JMS Queue.
 * 
 * @author bourretp
 */
public class JmsTopicPublisherSender implements ISender {

    private String m_instanceName;

    // The JNDI names of the JMS resources needed by this mediator
    private String m_topicConnectionFactoryName;

    private String m_topicName;

    // The needed resources retrieved via JNDI
    private volatile TopicConnectionFactory m_topicConnectionFactory;
    private volatile Topic m_topic;

    // Logger
    private LogService m_logger;

    // Retrieve the JMS QueueSession via JNDI
    public synchronized void start() {
        // Need to switch TCCL for JNDI lookup
        ClassLoader old = Thread.currentThread().getContextClassLoader();
        try {
            // Replace the TCCL with this bundle class loader (dynamic imports
            // must be enabled)
            Thread.currentThread().setContextClassLoader(
                    JmsTopicPublisherSender.class.getClassLoader());
            // Get JNDI initial context
            InitialContext context;
            try {
                context = new InitialContext();
            } catch (Exception e) {
                log(LogService.LOG_ERROR, "Cannot get JNDI initial context", e);
                throw new RuntimeException(e);
            }
            // Get JMS QueueConnectionFactory
            try {
                m_topicConnectionFactory = (TopicConnectionFactory) context
                        .lookup(m_topicConnectionFactoryName);
            } catch (Exception e) {
                log(LogService.LOG_ERROR,
                        "Cannot get JMS QueueConnectionFactory", e);
                throw new RuntimeException(e);
            }
            // Get JMS Queue
            try {
                m_topic = (Topic) context.lookup(m_topicName);
            } catch (Exception e) {
                log(LogService.LOG_ERROR, "Cannot get JMS Queue", e);
                throw new RuntimeException(e);
            }
            // Log success
            log(LogService.LOG_INFO, "Started");
            log(LogService.LOG_DEBUG, "queueConnectionFactory.name = "
                    + m_topicConnectionFactoryName);
            log(LogService.LOG_DEBUG, "queue.name = " + m_topicName);
        } finally {
            // Restore TCCL
            Thread.currentThread().setContextClassLoader(old);
        }
    }

    // Release references
    public synchronized void stop() {
        m_topicConnectionFactory = null;
        m_topic = null;
        // Log success
        log(LogService.LOG_INFO, "Stopped");
    }

    // Send Method
    public boolean send(Data data) {
        // Get the content of the data
        byte[] content = (byte[]) data.getContent();
        // Send it via JMS
        try {
            jmsSend(content);
            log(LogService.LOG_DEBUG, "Message sent via JMS : " + content);
        } catch (JMSException e) {
            // Log
            log(LogService.LOG_ERROR, "Cannot send message", e);
			return false;
        }
        return true;
    }

    // Send the specified data via JMS
    private void jmsSend(byte[] bytes) throws JMSException {
        TopicConnection connection = m_topicConnectionFactory
                .createTopicConnection();
        // TODO make this a little more configurable...
        TopicSession session = connection.createTopicSession(false,
                Session.AUTO_ACKNOWLEDGE);
        MessageProducer messageProducer = session.createPublisher(m_topic);
        // Create the JMS bytes message.
        BytesMessage message = session.createBytesMessage();
        message.writeBytes(bytes);
        // Send the message using the producer.
        messageProducer.send(message);
        
        // Close connection
        session.close();
        connection.close();
    }

    // Utility methods

    private void log(int level, String message, Throwable throwable) {
        m_logger.log(level, m_instanceName + " - " + message, throwable);
    }

    private void log(int level, String message) {
        log(level, message, null);
    }

}
